<template>
  <div class="html-extract-page">
    <div class="page-container">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>智能工具</el-breadcrumb-item>
        <el-breadcrumb-item>病历结构化提取</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="page-header">
        <h2 class="page-title">病历结构化提取工具</h2>
        <p class="page-description">
          将医院病历HTML内容转换为结构化JSON数据，支持快速解析与数据处理。
        </p>
      </div>

      <!-- 服务状态检查 -->
      <el-alert
        v-if="serviceStatus === 'error'"
        title="后端服务连接失败"
        type="error"
        description="无法连接到后端服务，请确保服务已启动"
        show-icon
        :closable="false"
        style="margin-bottom: 20px;"
      >
        <template #default>
          <div>
            无法连接到后端服务，请确保服务已启动并且地址配置正确
            <div class="mt-2">
              <el-button size="small" type="primary" @click="checkServiceStatus" :loading="checkingService" style="margin-right: 10px;">
                重试连接
              </el-button>
              <el-button size="small" type="info" @click="openBackendUrl" style="margin-right: 10px;">
                直接访问后端
              </el-button>
              <el-button size="small" type="success" @click="testExtractAPI">
                测试提取API
              </el-button>
            </div>
            <div class="mt-2 text-gray">
              当前后端地址: {{ api.apiClient.defaults.baseURL }}
            </div>
          </div>
        </template>
      </el-alert>

      <!-- Tool Section -->
      <section class="tool-section">
        <el-card class="tool-card" shadow="hover">
          <el-tabs v-model="activeTab" class="tool-tabs">
            <el-tab-pane label="文件上传方式" name="file">
              <el-upload
                class="upload-area"
                drag
                action="#"
                :auto-upload="false"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
                :limit="1"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传HTML格式的病历文件
                  </div>
                </template>
              </el-upload>
              <div class="action-bar">
                <el-button type="primary" @click="submitFile" :disabled="!fileList.length || loading">
                  <el-icon v-if="loading" class="loading-icon"><loading /></el-icon>
                  <span>{{ loading ? '处理中...' : '提取结构化数据' }}</span>
                </el-button>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="文本输入方式" name="text">
              <el-form>
                <el-form-item label="HTML内容">
                  <el-input 
                    v-model="htmlContent" 
                    type="textarea" 
                    :rows="8"
                    placeholder="请输入病历HTML内容"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitText" :disabled="!htmlContent || loading">
                    <el-icon v-if="loading" class="loading-icon"><loading /></el-icon>
                    <span>{{ loading ? '处理中...' : '提取结构化数据' }}</span>
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>

        <!-- Results Section -->
        <transition name="fade">
          <el-card v-if="result" class="result-card" shadow="hover">
            <template #header>
              <div class="result-header">
                <h3>结构化数据结果</h3>
                <el-button size="small" type="success" @click="copyToClipboard">
                  <el-icon><document-copy /></el-icon> 复制JSON
                </el-button>
              </div>
            </template>
            <div class="result-content">
              <pre class="json-result">{{ formattedResult }}</pre>
            </div>
          </el-card>
        </transition>
      </section>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, DocumentCopy, Loading } from '@element-plus/icons-vue'
import api from '../services/api.js'

// 状态管理
const activeTab = ref('file')
const htmlContent = ref('')
const fileList = ref([])
const result = ref('')
const loading = ref(false)
const serviceStatus = ref('checking') // checking, ok, error
const checkingService = ref(false) // 用于控制重试按钮的加载状态

// 检查后端服务是否正常运行
const checkServiceStatus = async () => {
  checkingService.value = true
  try {
    // 尝试所有可能的健康检查方法
    await api.healthService.checkHealthAll()
    serviceStatus.value = 'ok'
    console.log('后端服务连接正常')
    ElMessage.success('后端服务连接成功')
  } catch (error) {
    serviceStatus.value = 'error'
    console.error('后端服务连接失败:', error)
    console.log('请确认后端服务地址是否正确: ' + api.apiClient.defaults.baseURL)
    console.log('当前配置的API路径: ' + api.apiClient.defaults.baseURL + '/heart/healthy')
    
    // 显示更详细的错误信息
    if (error.response) {
      // 服务器返回了错误状态码
      console.log('状态码:', error.response.status)
      console.log('响应数据:', error.response.data)
      console.log('响应头:', error.response.headers)
    } else if (error.request) {
      // 请求已发送但没有收到响应
      console.log('请求已发送但没有收到响应:', error.request)
    } else {
      // 请求配置出错
      console.log('请求配置错误:', error.message)
    }
  } finally {
    checkingService.value = false
  }
}

// 组件挂载时检查服务状态
onMounted(() => {
  checkServiceStatus()
})

// 格式化JSON显示
const formattedResult = computed(() => {
  try {
    if (!result.value) return ''
    // 尝试解析JSON，如果已经是对象，先转为字符串
    const jsonObj = typeof result.value === 'string' 
      ? JSON.parse(result.value) 
      : result.value
    return JSON.stringify(jsonObj, null, 2)
  } catch (e) {
    // 如果解析失败，直接返回原始字符串
    return result.value
  }
})

// 文件上传处理
const handleFileChange = (uploadFile) => {
  console.log('文件已选择:', uploadFile)
  fileList.value = [uploadFile]
}

// 文件移除处理
const handleFileRemove = () => {
  fileList.value = []
}

// 提交文件处理
const submitFile = async () => {
  if (!fileList.value.length) {
    ElMessage.warning('请先选择文件')
    return
  }
  
  // 先检查健康状态
  if (serviceStatus.value !== 'ok') {
    try {
      await api.healthService.checkHealth()
      serviceStatus.value = 'ok'
    } catch (error) {
      ElMessage.error('无法连接到后端服务，请确保服务已启动')
      return
    }
  }
  
  loading.value = true
  try {
    const response = await api.htmlExtractionService.extractFromFile(fileList.value[0].raw)
    console.log('API响应:', response)
    result.value = response.data.data
    ElMessage.success('处理成功')
  } catch (error) {
    console.error('提取失败:', error)
    ElMessage.error(`提取失败: ${error.response?.data?.message || error.message}`)
    result.value = error.response?.data || error.message
  } finally {
    loading.value = false
  }
}

// 提交文本处理
const submitText = async () => {
  if (!htmlContent.value) {
    ElMessage.warning('请先输入HTML内容')
    return
  }
  
  // 先检查健康状态
  if (serviceStatus.value !== 'ok') {
    try {
      await api.healthService.checkHealth()
      serviceStatus.value = 'ok'
    } catch (error) {
      ElMessage.error('无法连接到后端服务，请确保服务已启动')
      return
    }
  }
  
  loading.value = true
  try {
    const response = await api.htmlExtractionService.extractFromText(htmlContent.value)
    console.log('API响应:', response)
    result.value = response.data.data
    ElMessage.success('处理成功')
  } catch (error) {
    console.error('提取失败:', error)
    ElMessage.error(`提取失败: ${error.response?.data?.message || error.message}`)
    result.value = error.response?.data || error.message
  } finally {
    loading.value = false
  }
}

// 复制结果到剪贴板
const copyToClipboard = () => {
  const textarea = document.createElement('textarea')
  textarea.value = formattedResult.value
  document.body.appendChild(textarea)
  textarea.select()
  document.execCommand('copy')
  document.body.removeChild(textarea)
  ElMessage.success('已复制到剪贴板')
}

// 打开后端URL
const openBackendUrl = () => {
  const url = api.apiClient.defaults.baseURL + '/api/heart/healthy'
  window.open(url, '_blank')
}

// 测试提取API
const testExtractAPI = () => {
  const url = api.apiClient.defaults.baseURL + '/api/medical/extract/test'
  window.open(url, '_blank')
}
</script>

<style scoped>
.html-extract-page {
  padding: 0;
  width: 100%;
}

.page-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 0 30px;
}

.page-header {
  margin: 20px 0 30px;
  width: 100%;
}

.page-title {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
}

.page-description {
  color: #606266;
  font-size: 16px;
}

.tool-section {
  margin-bottom: 40px;
  width: 100%;
}

.tool-card {
  margin-bottom: 20px;
  width: 100%;
}

.upload-area {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color .3s;
}

.upload-area:hover {
  border-color: #409EFF;
}

.el-icon--upload {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.el-upload__text em {
  color: #409EFF;
  font-style: normal;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

.action-bar {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.result-card {
  margin-top: 20px;
  width: 100%;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.result-content {
  padding: 10px 0;
}

.json-result {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #303133;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.loading-icon {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity .3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

.mt-2 {
  margin-top: 8px;
}

.text-gray {
  color: #909399;
  font-size: 14px;
}

@media (max-width: 768px) {
  .page-container {
    padding: 0 15px;
  }
  
  .page-title {
    font-size: 24px;
  }
}
</style> 